package it11.Capood.DataLogic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import android.content.Context;
import android.content.ContextWrapper;

public class Storage {
	
	private File myInternalSaveDataFile;
	private String FILENAME = "MySavedData";
	private String FILEPATH = "MyFileStorage";
	private HashSet<Message> messageList;
	
	private static Storage instance;

	private Storage (Context context) {
		
		ContextWrapper contextWrapper = new ContextWrapper(context);
		File directory = contextWrapper.getDir(FILEPATH, Context.MODE_PRIVATE);
		myInternalSaveDataFile = new File(directory, FILENAME);
		
		loadMessageList();
	}
	
	public static Storage getInstance(Context context) {
		if (instance == null){
			synchronized (Storage.class) {
				if (instance == null){
					instance = new Storage(context);
				}
			}
		}
		
		return instance;
	}
	
	public void addMessageToList (Message message) {
		this.messageList.add(message);
	}
	
	public HashSet<Message> getMessageList () {
		return this.messageList;
	}
	
	public File getInternalSaveDataFile () {
		return this.myInternalSaveDataFile;
	}
	
	public void deleteMessageFromList (Message msg ) {
		this.messageList.remove(msg);
	}
	
	public void saveMessageList () {
		try {
			FileOutputStream fos = new FileOutputStream(myInternalSaveDataFile);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			for (Message m : this.messageList) {
				oos.writeObject(m);
			}
			fos.close();
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	
	
	public void loadMessageList () {
		
		messageList = new HashSet<Message>();
		try {
			FileInputStream fis = new FileInputStream(myInternalSaveDataFile);
		    ObjectInputStream ois = new ObjectInputStream(fis);
		    Object obj = null;
			while ((obj = ois.readObject()) != null) {
				if (obj instanceof Message) {
					this.messageList.add((Message) obj);
				}	
			}
			fis.close();
			ois.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
}
